package com.hongliang.nio_c1.c1.bytebuffer;

import org.junit.Test;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

import static com.hongliang.nio_c1.utils.ByteBufferUtil.debugAll;

/**
 * 字符串与 ByteBuffer 互转
 * @author Hongliang Zhu
 * @create 2021-08-22 10:59
 */
public class ByteBuffer2String {

    /**
     * 1. 字符串转为ByteBuffer
     * 不会切换到读模式
     */
    @Test
    public void test1(){
        ByteBuffer buffer = ByteBuffer.allocate(16);
        buffer.put("hello".getBytes());
        debugAll(buffer);
    }

    /**
     * CharSet
     * 会自动切换到读取模式
     */
    @Test
    public void test2() {
        ByteBuffer buffer = StandardCharsets.UTF_8.encode("hello");
        debugAll(buffer);
    }

    /**
     * warp
     * 会自动切换到读取模式
     */
    @Test
    public void test3() {
        ByteBuffer buffer = ByteBuffer.wrap("hello".getBytes());
        debugAll(buffer);
    }

    /**
     * 转为字符串
     */
    @Test
    public void test4() {
        ByteBuffer buffer = StandardCharsets.UTF_8.encode("hello");
        String s = StandardCharsets.UTF_8.decode(buffer).toString();
        System.out.println(s);

    }

}
